package com.chinasoft.controller;

import com.alibaba.fastjson.JSONArray;
import com.chinasoft.pojo.Role;
import com.chinasoft.pojo.User;
import com.chinasoft.service.RoleService;
import com.chinasoft.service.UserService;
import com.chinasoft.tools.Contants;
import com.chinasoft.tools.PageSupport;
import com.mysql.cj.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger log = Logger.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    // 6.29
    @RequestMapping(value = "/login.html")
    public String login() {
        log.info("userController welcome Page Loading.............");
        return "login";
    }

    @RequestMapping("/dologin.html")
    public String doLogin(@RequestParam String userCode, @RequestParam String userPassword, HttpSession session, HttpServletRequest request) {
        log.info("doLogin=================================");
        User user = userService.login(userCode, userPassword);
        if (user != null) {
            log.info("found UserInfo");
            session.setAttribute(Contants.USER_SESSION, user);
            return "redirect:/user/main.html";
        } else {
            log.info("Not found UserInfo");
            return "login";
        }
    }

    @RequestMapping("/main.html")
    public String main(HttpSession session) {
        log.info("main==========================");
        if (session.getAttribute(Contants.USER_SESSION) == null) {
            log.info("userSession为空");
            return "redirect:/user/login.html";
        } else {
            log.info("找到了userSession");
        }
        return "frame";
    }

    //查看角色信息
    @RequestMapping("/userlist.html")
    public String getUserList(Model model,
                              @RequestParam(value = "queryUserName",required = false)String queryUserName,
                              @RequestParam(value = "queryUserRole",required = false)String queryUserRole,
                              @RequestParam(value = "pageIndex",required = false)String pageIndex){
        log.info("getUserList ---- > queryUserName: " + queryUserName);
        log.info("getUserList ---- > queryUserRole: " + queryUserRole);
        log.info("getUserList ---- > pageIndex: " + pageIndex);
        int _queryUserRole = 0;
        //设置页面容量
        int pageSize = Contants.pageSize;
        //当前页码
        int currentPageNo = 1;

        if(queryUserName == null){
            queryUserName = "";
        }
        if(queryUserRole != null && queryUserRole.equals("")){
            _queryUserRole = Integer.parseInt(queryUserRole);
        }
        if(pageIndex != null){
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            }catch (Exception e){
                return "redirect:/user/syserror.html";
            }
        }
        //总用户数量（表）
        int totalCount = userService.getUserCount(queryUserName,_queryUserRole);
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);

        int totalPageCount = pages.getTotalPageCount();
        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        List<User> userList = null;
        userList = userService.getUserList(queryUserName,_queryUserRole,currentPageNo,pageSize);
        model.addAttribute("userList",userList);
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        model.addAttribute("roleList", roleList);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", currentPageNo);

        return "userlist";
    }


    @RequestMapping(value="useradd.html",method = RequestMethod.GET)
    public  String addUser(@ModelAttribute("user") User user){
        return "useradd";
    }

    //出现错误的页面
    @RequestMapping("/syserror.html")
    public String sysError(){
        return "syserror";
    }

    //保存数据
    @RequestMapping(value = "/useraddsave.html",method = RequestMethod.POST)
    public String addUserSave(User user,HttpSession session){
        user.setCreatedBy(((User)session.getAttribute(Contants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        if(userService.addUser(user)){
            return "redirect:/user/userlist.html";
        }
        return "useradd";
    }

    //关于json的知识
    @RequestMapping(value = "/ucexist.html")
    @ResponseBody
    public Object userCodeIsExit(@RequestParam String userCode){
        log.info("userCodeIsExit userCode===================== "+userCode);
        HashMap<String,String> resultMap = new HashMap<String,String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            resultMap.put("userCode","exist");
        }
        else {
            User user = userService.selectUserCodeExist(userCode);
            if (user != null){
                resultMap.put("userCode","exist");
            }
            else {
                resultMap.put("userCode","noexist");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping(value="usermodify.html",method = RequestMethod.GET)
    public String getUserById(@RequestParam String uid,Model model){
        log.info("getUserById uid================" + uid );
        User user = userService.getUserById(uid);
        //传输数据到下一个usermodify
        model.addAttribute(user);
        return "usermodify";
    }

    @RequestMapping(value = "usermodifysave.html",method = RequestMethod.POST)
    public String modifyUserSave(User user,HttpSession session){
        log.info("modifyUserSave userid=========================" + user.getId());
        user.setModifyBy(((User)session.getAttribute(Contants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
        return "usermodify";
    }


    //7.1第三天
    //@PathVariable中的属性名要与value中的的{}里的一致
    //该方法用的是第二种网址呈现方式，
    /**
     * 如第一种：.....user？id=1234
     * 第二种：...user/view/1234
     * @param id 用于传参
     * @param model
     * @return
     */
    @RequestMapping(value = "view/{id}",method = RequestMethod.GET)
    public String view(@PathVariable String id,Model model){
        log.info("view id========================");
        User user = userService.getUserById(id);
        model.addAttribute(user);
        return "userview";
    }


    //以下是第一天的练习
/*    @RequestMapping("/welcome")
    public String welcome(@RequestParam String username) {
        log.info("welcome,username:" + username);
        return "index";
    }


    @RequestMapping("/helloworld")
    public ModelAndView index(String username) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("username", username);
        mv.setViewName("index");
        return mv;
    }

    @RequestMapping("welcometj")
    public String index2(String username, Model model) {
        log.info("index2,username:" + username);
        model.addAttribute("username2", username);
        return "index";
    }

    @RequestMapping("WTF")
    public String index3(String username, Map<String, Object> model) {
        log.info("index3,username:" + username);
        model.put("username3:", username);
        return "index";
    }

    @RequestMapping("user")
    public String index4(String username, String pwd,Model model){
        System.out.println("传对象");
        User user = new User();
        user.setUserName(username);
        user.setUserPassword(pwd);
        model.addAttribute("currentUser", user);
        return "index";
    }*/

}
